/**
 * Created by Brook on 2020/4/9.
 */

(function () {
    const async = require('async');
    const moment = require('moment');
    const sql_config = require('../../serverconfig.js');
    const model_sql = require('../../tool/db_helper.js').init(sql_config.Model_Config);
    const SQL_TXT = sql_config.SQL_TXT;
    const urlencode = require('urlencode');
    const https = require('https');
    const http = require('http');
    const valid = require('url-valid');
    const uuid = require('node-uuid');


    //模型上传 回传参数
    const Parsedata = {
        "message": "请求成功",
        "data": {
            "status": 200,
            "status_text": "",
            "error_message": null,
            "error_stacks": null
        }
    };

    const Successdata = {
        "message": "请求成功",
        "data": {
            "code": 200,
            "message": '请求成功',
            "data":""
        }
    };

    //【记录】 - 渲染平台 - 模型上传
    exports.post_xrParse = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            //判断请求地址
            check_request_ip:['check_pars', function (cb, result) {
                const ip = getClientIP(req);

                //if (!/::1|106.52.70.77|193.112.44.252|218.23.36.18/.test(ip)) {
                //     data.data.status = 201;
                //     data.data.status_text = '仅接受指定服务器的文件';
                //     res.json(data);
                // } else {
                cb(null, [])
                // }
            }],
            //判断请求参数
            check_request_parameter:['check_request_ip', function (cb, result) {
                const {filePath, mac} = result.check_pars;
                if (!filePath || !mac) {
                    Parsedata.data.status = 202;
                    Parsedata.data.status_text = '参数不正确';
                    res.json(Parsedata);
                } else {
                    cb(null, []);
                };
            }],
            //判断下载地址参数
            check_path:['check_request_parameter', function (cb, result) {
                const info = result.check_pars;
                info.filePath = info.filePath.replace(/\+/g,' ');  //URL中的+传到后台之后变成空格

                const filepaths = urlencode.decode(info.filePath);
                const str =encodeURI(filepaths);


                //判断模型地址
                valid(str, function (err, valid) {if (err) throw err;
                    if (!valid) {
                        Parsedata.data.status = 204;
                        Parsedata.data.status_text = '模型下载地址参数异常';
                        res.json(Parsedata);
                    } else {
                        cb();
                    };
                });
            }],
            //判断模型格式
            get_suffix:['check_path', async function (cb, result) {
                const info = result.check_pars;
                let suffix = "";
                let modelname = "";
                const ha = new httpAsync();
                const res_path = await ha.GetAsync(info.filePath);
                if (!res_path.headers['content-disposition']) {
                    console.log('Warning Res.Headers')
                    const filepath = urlencode.decode(info.filePath);
                    suffix = filepath.split('.')[filepath.split('.').length - 1];
                    modelname = filepath.split('/')[filepath.split('/').length - 1];
                } else {
                    const filename = res_path.headers['content-disposition'].match(/(filename=(.*))/)[2];
                    suffix = filename.split('.')[filename.split('.').length - 1];
                    modelname = filename;
                };
                console.log("model suffix ：", suffix);
                info["suffix"] = suffix;
                info["filename"] = modelname;
                cb(null, info)
            }],
            check_model_format:['get_suffix', function (cb, result) {
                if (!/skp|rvt|3dm|pla|rfa/.test(result.get_suffix.suffix)) {
                    Parsedata.data.status = 203;
                    Parsedata.data.status_text = '模型格式异常';
                    res.json(Parsedata);
                } else {
                    result.get_suffix.gltfstate = '1';
                    cb(null, result.get_suffix);
                };
            }],
            //正确响应
            response_data:['check_model_format', function (cb, result) {
                Parsedata.data.status = 200;
                Parsedata.data.status_text = '待转换Gltf...';
                console.log("Response request data success ...")
                res.json(Parsedata);
                cb(null, [])
            }],
            insert_db:['response_data', function(cb, result) {
                let model_data = [];
                model_data = [
                    uuid.v1(),
                    urlencode.decode(result.get_suffix.filePath),
                    result.get_suffix.suffix,
                    result.get_suffix.filename,
                    result.check_pars.mac,
                    result.check_model_format.gltfstate,
                    moment().format('YYYYMMDD'),
                    moment().format('YYYY-MM-DD HH:mm:ss')
                ];


                model_sql.query(SQL_TXT.insert_xrmodel_info,model_data,function(db_err,db_result){
                    console.log("insert sql success ... ")
                    db_err?cb(db_err):cb(null,db_result);
                });
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    }

    //【查询】 - 渲染平台 - 获取Gltf列表
    exports.post_xrGetGltf = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            check_data:['check_pars', function (cb,result) {
                model_sql.query(SQL_TXT.check_gltf_data_mac,[result.check_pars.mac],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            data_handle:['check_data', function (cb, result) {
                if (result.check_data.length == 0){
                    Successdata.data.code = 201;
                    Successdata.data.message = '无效的MAC';
                    Successdata.data.data = "";
                    res.json(Successdata);
                    cb('无效的MAC')
                } else {
                    cb(null,result.check_data);
                };
            }],
            response_data:['data_handle', function (cb, result) {
                Successdata.data.code = 200;
                Successdata.data.code = "请求成功";
                Successdata.data.data = result.data_handle;
                res.json(Successdata);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    }

    //【查询】 - 渲染平台 - 获取任务
    exports.post_xrGetData = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            //获取任务
            get_data:['check_pars', function (cb, result) {
                model_sql.query(SQL_TXT.get_xrgltf_data_task,[],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //判断是否有任务
            check_data:['get_data', function (cb, resulrt) {
                if (resulrt.get_data.length == 0) {
                    Successdata.data.code = 21;
                    Successdata.data.message = '中心列表无数据';
                    Successdata.data.data = "";
                    console.log("Response request data success ...")
                    res.json(Successdata);
                    cb('中心列表中无数据')
                } else {
                    cb(null, [])
                };
            }],
            //绑定相关参数
            up_data:['check_data', function (cb, result) {
                model_sql.query(SQL_TXT.up_xrgltf_data_task,['2','21','正在转换Gltf...',result.get_data[0].uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //回传数据
            response_data:['up_data', function (cb, result) {
                Successdata.data.code = 200;
                Successdata.data.message = '获取数据成功';
                Successdata.data.data = result.get_data;
                console.log("Response request data success ...")
                res.json(Successdata);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    }

    //【查询】 - 渲染平台 - 获取Rvt任务
    exports.post_xrGetRvtData = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            //获取任务
            get_data:['check_pars', function (cb, result) {
                model_sql.query(SQL_TXT.get_xrrvtgltf_data_task,[],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //判断是否有任务
            check_data:['get_data', function (cb, resulrt) {
                if (resulrt.get_data.length == 0) {
                    Successdata.data.code = 21;
                    Successdata.data.message = '中心列表无数据';
                    Successdata.data.data = "";
                    console.log("Response request data success ...")
                    res.json(Successdata);
                    cb('中心列表中无数据')
                } else {
                    cb(null, [])
                };
            }],
            //绑定相关参数
            up_data:['check_data', function (cb, result) {
                model_sql.query(SQL_TXT.up_xrgltf_data_task,['2','21','正在转换Gltf...',result.get_data[0].uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //回传数据
            response_data:['up_data', function (cb, result) {
                Successdata.data.code = 200;
                Successdata.data.message = '获取数据成功';
                Successdata.data.data = result.get_data;
                console.log("Response request data success ...")
                res.json(Successdata);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    }


    //【记录】 - 渲染平台 - 保存Gltf地址
    exports.post_xrUpGltf = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            check_data:['check_pars', function (cb,result) {
                model_sql.query(SQL_TXT.check_xrgltf_data_uuid,[result.check_pars.uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            up_shvpath:['check_data', function (cb, result) {
                if (result.check_data.length == 0){
                    Successdata.data.code = 201;
                    Successdata.data.message = '无效的UUID';
                    Successdata.data.data = "";

                    res.json(Successdata);
                    cb('uuid异常')
                } else {
                    let {gltfPath, binPath, shvPath} = result.check_pars;

                    if (gltfPath == ""){
                        gltfPath = result.check_data[0].gltfpath;
                    };
                    if (binPath == ""){
                        binPath = result.check_data[0].binpath;
                    };
                    if (shvPath == ""){
                        shvPath = result.check_data[0].shvpath;
                    };

                    model_sql.query(SQL_TXT.up_xrgltf_data_shvpath,[gltfPath, binPath, shvPath, result.check_pars.uuid],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                };
            }],
            response_data:['up_shvpath', function (cb, result) {
                Successdata.data.code = 200;
                Successdata.data.message = '数据更新成功';
                Successdata.data.data = "";

                res.json(Successdata);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    }

    //【更新】 - 渲染平台 - 转换状态
    exports.post_xrUpState = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            //获取uuid
            get_fileID:['check_pars', function (cb, result) {
                const {uuid} = result.check_pars;
                //查询数据
                model_sql.query(SQL_TXT.check_xrgltf_data_uuid, [uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //更新状态
            up_state:['get_fileID', function (cb, result) {
                if (result.get_fileID.length == 0) {
                    Successdata.data.code = 201;
                    Successdata.data.message = '无效的UUID';
                    Successdata.data.data = "";

                    res.json(Successdata);
                } else {
                    let {uuid,parsingCode,parsingMessage,parsingType} = result.check_pars;
                    //查询数据
                    model_sql.query(SQL_TXT.up_xrgltf_data_task, [parsingType, parsingCode, parsingMessage, uuid],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                };
            }],
            response_data:['up_state', function (cb, result) {
                Successdata.data.code = 200;
                Successdata.data.message = '数据更新成功';
                Successdata.data.data = "";

                res.json(Successdata);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    }


    //HTTP请求获取Headers
    class httpAsync {
        varructor() {
        }
        async GetAsync(url) {

            const filepaths = urlencode.decode(url);
            const type = filepaths.split("://");
            const str =encodeURI(filepaths);

            const promise = new Promise(resolve => {
                if (type[0] == 'http') {
                    http.get(str, res => {
                        //console.log(res)
                        resolve(res);
                    });
                } else {
                    https.get(str, res => {
                        //console.log(res)
                        resolve(res);
                    });
                };
            });
            return promise;
        }
    }

    /**
     * @getClientIP
     * @desc 获取用户 ip 地址
     * @param {Object} req - 请求
     */
    function getClientIP(req) {
        return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
            req.connection.remoteAddress || // 判断 connection 的远程 IP
            req.socket.remoteAddress || // 判断后端的 socket 的 IP
            req.connection.socket.remoteAddress;
    };
}).call(this);
